# coding=utf-8
import logging
import mimetypes
import os
from wsgiref.util import FileWrapper
from django.http.response import HttpResponse
from django.utils.http import urlquote
from xls_demo.utils import create_failure_dict

class FixedFileWrapper(FileWrapper):
    def __iter__(self):
        self.filelike.seek(0)
        return self


def file_response(func):
    def _inner(request, *args, **kwargs):
        result = func(request, *args, **kwargs)

        wrapper = FixedFileWrapper(open(result['path'], 'rb'))
        content_type = mimetypes.guess_type(result['name'])[0]
        response = HttpResponse(wrapper, content_type)
        response['Content-Length'] = os.path.getsize(result['path'])
        filename = urlquote(os.path.basename(result['name']))
        disp = "attachment; filename=%s" % filename
        response['Content-Disposition'] = disp
        return response

    return _inner